/**
 * 
 */
package cn.erp.app.controller;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import cn.erp.app.service.MenuService;
import cn.erp.app.vo.menu.MenuVo;
import cn.erp.common.model.SystemMenu;
import cn.erp.common.model.SystemUser;

import com.jfinal.common.controller.BaseController;
import com.jfinal.ext.ret.ReqResult;
import com.jfinal.ext.route.ControllerBind;

/**
 * @author YuanZhiHua
 *
 */

@ControllerBind(controllerKey = "/auth", viewPath = "/")
public class AuthController extends BaseController {

	public void login() {
		render("login.html");
	}

	public void doLogin() {
		String username = getPara("login_name");
		String pwd = getPara("pwd");
		Subject currentUser = SecurityUtils.getSubject();
		// if ( !currentUser.isAuthenticated() ) {
		UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
		String msg = "";
		try {
			currentUser.login(token);
			SystemUser user = getCurrentUserFromDb();
			getSession().setAttribute("currentUser", user);
			List<MenuVo> menus = MenuService.me.getMenus();
			getSession().setAttribute("menus", menus);
			
//			 List<SysMenu> menus = SysMenu.dao.getMyMenus(user.getId());
			
			// redirect("/");
			renderJson(ReqResult.LOGIN_SUCCESS);
			return;
		} catch (UnknownAccountException uae) {
			msg = "用户名不存在";
		} catch (IncorrectCredentialsException ice) {
			msg = "用户名或者密码不正确";
		} catch (LockedAccountException lae) {
			msg = "帐号已经被锁定";
		}
		// setAttr("loginMsg", msg);
		renderJson(ReqResult.LOGIN_FAILED.setMsg(msg));
		// render("login.html");
		// } else {
		// User user = getCurrentUserFromDb();
		// getSession().setAttribute("currentUser", user);
		//
		// //获取菜单
		// MenuTabVo vo = getMenu();
		// getSession().setAttribute("menu", vo);
		//
		// //字典数据放到session中
		// getSession().setAttribute("dict",DictService.me.getDict());
		// redirect("/");
		// return;
		// }
	}

	public void doLoginOut() {
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		// if ( !currentUser.isAuthenticated() ) {
		redirect("/auth/login");
		// } else {
		// User user = getCurrentUserFromDb();
		// getSession().setAttribute("currentUser", user);
		//
		// //获取菜单
		// MenuTabVo vo = getMenu();
		// getSession().setAttribute("menu", vo);
		//
		// //字典数据放到session中
		// getSession().setAttribute("dict",DictService.me.getDict());
		// redirect("/");
		// return;
		// }
	}
}
